package com.controllet;

import com.github.pagehelper.PageHelper;
import com.pojo.User;
import com.service.UserService;
import com.util.ResulDate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
public class UserController {

    @Resource
    UserService userService;

    @GetMapping("/userAll")
    public List<User> userAll(Model model){
        PageHelper.startPage(1,2);
        List<User> userAll = userService.getUserAll();
        return userAll;
    }

    @RequestMapping("/index")
    public String index(Model model){
        List<User> userAll = userService.getUserAll();
        //HttpSession session = request.getSession();
        model.addAttribute("userAll",userAll);
       return "index";
    }

    @RequestMapping("/del")
    @ResponseBody
    public ResulDate delUser(int id){
        int i =userService.delUserById(id);
        ResulDate<User> resulDate = new ResulDate<User>();
        if(i>0){
            resulDate.setCode(200);
            resulDate.setMsg("删除成功");
        }else {
            resulDate.setCode(500);
            resulDate.setMsg("删除失败");
        }
         return resulDate;
    }

    @RequestMapping("/userAdd")
    @ResponseBody
    public ResulDate addUser(User user){
        int i = userService.addUserById(user);
        ResulDate<User> resulDate = new ResulDate<User>();
        if(i>0){
            resulDate.setCode(200);
            resulDate.setMsg("新增成功");
        }else {
            resulDate.setCode(500);
            resulDate.setMsg("新增失败");
        }
        return resulDate;
    }

    @RequestMapping("/showUser")
    public String ShowUser(int id, Model model){
        User user = userService.getUserById(id);
        model.addAttribute("user",user);
        return "showUser";
    }

    @RequestMapping("/showUser1")
    @ResponseBody
    public User showUser1(int id, Model model){
        User user = userService.getUserById(id);
        return user;
    }

    @RequestMapping(value = "/userUpdate")
    @ResponseBody
    public ResulDate editUser(User user){
        int i = userService.editUserById(user);
        ResulDate<User> resulDate = new ResulDate<User>();
        if(i>0){
            resulDate.setCode(200);
            resulDate.setMsg("新增成功");
        }else {
            resulDate.setCode(500);
            resulDate.setMsg("新增失败");
        }
        return resulDate;
    }
}
